package com.ruoyi.youtian.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.enums.DelFlagEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.youtian.domain.Template;
import com.ruoyi.youtian.domain.TemplateDetail;
import com.ruoyi.youtian.domain.vo.OperateRuleVo;
import com.ruoyi.youtian.domain.vo.TemplateSceneVO;
import com.ruoyi.youtian.domain.vo.TemplateVO;
import com.ruoyi.youtian.mapper.TemplateDetailMapper;
import com.ruoyi.youtian.mapper.TemplateMapper;
import com.ruoyi.youtian.service.ITemplateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 模板Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-07
 */
@Service
@Slf4j
@Transactional
public class TemplateServiceImpl implements ITemplateService
{
    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private TemplateDetailMapper templateDetailMapper;




    /**
     * 查询模板
     *
     * @param templateId 模板主键
     * @return 模板
     */
    @Override
    public TemplateVO selectTemplateByTemplateId(Long templateId){
        Template template = templateMapper.selectTemplateByTemplateId(templateId);
        TemplateDetail templateDetail=new TemplateDetail();
        templateDetail.setTemplateId(template.getTemplateId());
        List<TemplateDetail> templateDetails = templateDetailMapper.selectTemplateDetailList(templateDetail);
        if (!CollectionUtils.isEmpty(templateDetails)) {
            templateDetails.forEach(detail -> {
                if(StringUtils.isNotEmpty(detail.getOperateRule())){
                    OperateRuleVo operateRuleVo = JSON.parseObject(detail.getOperateRule(),OperateRuleVo.class);
                    detail.setOperateRuleObj(operateRuleVo);
                }
            });
        }
        TemplateVO templateVO=new TemplateVO();
        templateVO.setTemplate(template);
        templateVO.setTemplateDetailList(templateDetails);
        return templateVO;

    }

    @Override
    public Template getById(Long templateId) {
        return templateMapper.selectTemplateByTemplateId(templateId);
    }


    /**
     * 查询模板列表
     *
     * @param template 模板
     * @return 模板
     */

    @Override
    public List<Template> selectTemplateList(Template template)
    {
        return templateMapper.selectTemplateList(template);
    }

    /**
     * 新增模板
     *
     * @param templateVO 模板
     * @return 结果
     */
    @Override
    public long insertTemplate(TemplateVO templateVO)
    {
        Template template = templateVO.getTemplate();
        List<TemplateDetail> templateDetailList = templateVO.getTemplateDetailList();
//        //新增数据 创建时间 更新时间相同, 创建人和修改人相同
        String userName = templateVO.getCreateBy();
        Date nowDate = templateVO.getCreateTime();
//        template.setCreateTime(nowDate);
//        template.setUpdateTime(nowDate);
//
        long insertResult = templateMapper.updateTemplate(template);
        if (Objects.equals(insertResult,0L)) {
            throw new ServiceException("修改失败");
        }
        Long templateId = template.getTemplateId();


        for (TemplateDetail templateDetail : templateDetailList) {
            templateDetail.setTemplateId(templateId);
            templateDetail.setCreateTime(nowDate);
            templateDetail.setCreateBy(userName);
            templateDetail.setUpdateTime(nowDate);
            templateDetail.setUpdateBy(userName);
            templateDetail.setDeptId(templateVO.getDeptId());

            // 各连线间新增条件表达式
            if(templateDetail.getOperateRuleObj() !=null){
                templateDetail.setFormulaText(templateDetail.getOperateRuleObj().getFormulaText());
                //JSON.toJSON(templateDetail.getOperateRuleObj()).toString();
                //System.out.println("=====>"+JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
                templateDetail.setOperateRule(JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
            }
            templateDetailMapper.insertTemplateDetail(templateDetail);
        }

        log.info("templateId: "+templateId+" 插入详情数据条数: "+templateDetailList.size());

        return templateId;
    }

    /**
     * 修改模板
     *
     * @param templateVO 模板
     * @return 结果
     */
    @Override
    public int updateTemplate(TemplateVO templateVO ) {

        //修改日期为当前时间
        Date nowDate = DateUtils.getNowDate();
        templateVO.getTemplate().setUpdateTime(nowDate);
        //更新模板
        int result = templateMapper.updateTemplate(templateVO.getTemplate());
        //删除过去的模板详情
        templateDetailMapper.deleteTemplateDetailByTemplateDetailId(templateVO.getTemplate().getTemplateId());


        if (!CollectionUtils.isEmpty(templateVO.getTemplateDetailList())) {
            templateVO.getTemplateDetailList().forEach(templateDetail -> {
                templateDetail.setTemplateId(templateVO.getTemplate().getTemplateId());
                templateDetail.setUpdateBy(templateVO.getTemplate().getUpdateBy());
                // 各连线间新增条件表达式
                if(templateDetail.getOperateRuleObj() !=null){
                    templateDetail.setFormulaText(templateDetail.getOperateRuleObj().getFormulaText());
                    //JSON.toJSON(templateDetail.getOperateRuleObj()).toString();
                    //System.out.println("=====>"+JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
                    templateDetail.setOperateRule(JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
                }
                //更新模板详情
                templateDetailMapper.insertTemplateDetail(templateDetail);
            });

        }
        return result;
    }

    /**
     * 批量删除模板
     *
     * @param templateIds 需要删除的模板主键
     * @return 结果
     */
    @Override
    public int deleteTemplateByTemplateIds(Long[] templateIds)
    {
        if (Objects.isNull(templateIds)||templateIds.length==0) {
            throw new ServiceException("删除数据失败");
        }
        for (Long templateId : templateIds) {
            deleteTemplateByTemplateId(templateId);
        }
        return templateIds.length;
    }

    /**
     * 删除模板信息
     *
     * @param templateId 模板主键
     * @return 结果
     */
    @Override
    public int deleteTemplateByTemplateId(Long templateId)
    {
        Template template =new Template();
        template.setTemplateId(templateId);
        //2 代表删除
        template.setDelFlag(DelFlagEnum.DELETE.getCode());
        templateMapper.updateTemplate(template);
        TemplateDetail templateDetail=new TemplateDetail();
        templateDetail.setTemplateId(templateId);
        templateDetail.setDelFlag(DelFlagEnum.DELETE.getCode());
        return templateDetailMapper.updateTemplateDetailByTemplateId(templateDetail);


    }
    @Override
    public List<TemplateSceneVO> selectSceneSourcePoint(TemplateSceneVO templateSceneVO){
        return templateMapper.selectSceneSourcePoint(templateSceneVO);
    }


    @Override
    public List<TemplateSceneVO> selectSceneTargetPoint(TemplateSceneVO templateSceneVO){
        return templateMapper.selectSceneTargetPoint(templateSceneVO);
    }

    @Override
    public int copyTemplate(Template template) {
        Long sourceTemplateId = template.getTemplateId();
        template.setTemplateId(null);
        int result = templateMapper.insertTemplate(template);
        if (Objects.equals(0,result)) {
            return 0;
        }
        Long templateId = template.getTemplateId();
        TemplateDetail templateDetail=new TemplateDetail();
        templateDetail.setTemplateId(sourceTemplateId);
        List<TemplateDetail> templateDetails = templateDetailMapper.selectTemplateDetailList(templateDetail);
        if (CollectionUtils.isEmpty(templateDetails)) {
            templateDetails.forEach(detail->{
                detail.setTemplateDetailId(null);
                detail.setTemplateId(templateId);
                detail.setDeptId(detail.getDeptId());
                detail.setCreateBy(detail.getCreateBy());
                // 各连线间新增条件表达式
                if(templateDetail.getOperateRuleObj() !=null){
                    templateDetail.setFormulaText(templateDetail.getOperateRuleObj().getFormulaText());
                    //JSON.toJSON(templateDetail.getOperateRuleObj()).toString();
                    //System.out.println("=====>"+JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
                    templateDetail.setOperateRule(JSON.toJSON(templateDetail.getOperateRuleObj()).toString());
                }
                templateDetailMapper.insertTemplateDetail(detail);
            });

        }
        return result;
    }

    @Override
    public int shareTemplate(Template template) {
        return templateMapper.shareTemplate(template);
    }
}
